﻿using System;
using System.Windows.Forms;
using PersonalAccoutingProgram.Data;
using System.Linq;

public partial class EnterExpenses : Form
{ 
    private string userName;

    public EnterExpenses(string userName)
    { 
        InitializeComponent();
        InitializeControls(userName); 
    }

    private void InitializeControls(string userName)
    {
        CategoriesInitialize();
        InitializeDatePicker();
        this.userName = userName;        
    }

    private void InitializeDatePicker()
    {
        dateTimePicker.Format = DateTimePickerFormat.Custom;
        dateTimePicker.CustomFormat = DateFormat.DATE_TIME_FORMAT;
    }

    private void CategoriesInitialize()
    {
        var allCategories =
        CategoryDataClassesDataContext.GetAllCategories();
        comboCategory.Items.AddRange(allCategories.ToArray());       
    }

    private void EnterExpenses_Load(object sender, EventArgs e)
    {
    }

    private void btnAdd_Click(object sender, EventArgs e)
    {
        try
        {
            if (comboCategory.SelectedIndex == -1)
            {
                throw new ArgumentException("Not selected category!");
            }
            if (tbAmount.Text == String.Empty)
            {
                throw new ArgumentException("The amount is not entered!");
            }
            if (DataValidator.isAmountValid(tbAmount.Text))
            { 
                string amountForAdd = String.Format("{0:0.00}", tbAmount.Text);
                decimal amount = decimal.Parse(amountForAdd);
                var userID = UserDataClassesDataContext.GetUserID(userName);
                int categoryID = comboCategory.SelectedIndex + 1;
                int userIntID = userID.First(id => id > 0);
                DateTime date = DateTime.Parse(dateTimePicker.Text);
                ExpenseDataClassesDataContext.AddNewExpenses(
                    amount, categoryID, userIntID, date);
                MessageBox.Show("Added successfully!");              
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

    private void btnCancel_Click(object sender, EventArgs e)
    {
        this.Dispose();
    }

    private void tbAmount_KeyPress(object sender, KeyPressEventArgs e)
    {
        DataValidator.ValidateAmount(e);
    }
}